/*
*  This file is part of mangusta
*
*  mangusta is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  mangusta is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with mangusta; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  US
*
*  Author: <antonino.calderone@ericsson.com>, <acaldmail@gmail.com>
*
*/


/* -------------------------------------------------------------------------- */

#include "nu_lang_defs.h"
#include "nu_rt_prog_ctx.h"
#include "nu_stmt_func.h"
#include "nu_functions.h"
#include "nu_error_codes.h"
#include "nu_expr_literal.h"


/* -------------------------------------------------------------------------- */

namespace nu
{


/* -------------------------------------------------------------------------- */

stmt_func_t::stmt_func_t(
   prog_ctx_t & ctx,
   const std::string& id,
   const std::string& ret_type)
   :
   stmt_t(ctx),
   _id(id),
   _ret_type(ret_type)
{

   //Get a reference to global function set
   auto & funcs = functions_t::get_instance();

   //Search function prototype by name
   //
   auto i = ctx.proc_prototypes.data.find(id);

   syntax_error_if(
      (i != ctx.proc_prototypes.data.end() &&
       i->second.first.get_line() != ctx.compiletime_pc.get_line()),
      "Function '" + id + "' already defined");

   // Remove an old declaration for replacing its prototype
   if (i != ctx.proc_prototypes.data.end())
      ctx.proc_prototypes.data.erase(i);

   auto it = ctx.proc_prototypes.data.insert(
                std::make_pair(
                   id,
                   std::make_pair(
                      ctx.compiletime_pc,
                      func_prototype_t())
                )
             );

   assert(it.second);

   auto & prototype = it.first->second.second;
   prototype.ret_type = ret_type;

   // Create metadata for the function (including begin-line and its name)
   ctx.procedure_metadata.compile_begin(ctx.compiletime_pc, id);

   // Create an execution object (using a lamda)
   auto this_func = [](
                       rt_prog_ctx_t & ctx,
                       const std::string& name,
                       const func_args_t & args)
                    -> variant_t
   {
      // Run the function
      ctx.program().run(name, args);

      // Retrieve the return value
      auto i = ctx.function_retval_tbl.find(name);

      syntax_error_if(
         i == ctx.function_retval_tbl.end(),
         "Return value '" + name + "' not defined");

      auto & stack = i->second;
      auto ret = stack.front();
      stack.pop_front();

      if (stack.empty())
         ctx.function_retval_tbl.erase(name);

      return ret;
   };

   // Register this execution object as a function
   // (just like any other global function,
   //  including precompiled built-in ones)
   if (! funcs.is_defined(id))
      funcs.define(id, this_func);

   ctx.parsing_scope.push(PROGLANG_STMT_FUNCTION);
   ctx.parsing_func.push(id);

}


/* -------------------------------------------------------------------------- */

void stmt_func_t::run(rt_prog_ctx_t & ctx)
{
   auto & subctx = ctx.procedure_metadata;
   auto handle = subctx.begin_find(ctx.runtime_pc);

   rt_error_code_t::get_instance().throw_if(
      !handle,
      ctx.runtime_pc.get_line(),
      rt_error_code_t::E_FUNC_UNDEF,
      _id);

   auto scope_id = ctx.proc_scope.get_scope_id();

   // Skip function body if we are in the global scope
   if (scope_id.empty())
   {
      handle->flag[instrblock_t::EXIT] = true;
      ctx.go_to(handle->pc_end_stmt);
      return;
   }

   else
   {
      handle->flag[instrblock_t::EXIT] = false;
   }

   ctx.go_to_next();
}


/* -------------------------------------------------------------------------- */

void stmt_func_t::define(
   const std::string& var,
   const std::string& var_type,
   bool reference,
   bool array_type,
   vec_size_t vect_size,
   prog_ctx_t & ctx,
   const std::string& id,
   const std::string& ret_type)
{
   assert(_id == id);
   (void)ret_type;

   syntax_error_if(
      _vars_rep_check.find(var) != _vars_rep_check.end(),
      "Cannot reuse a variable name in subroutine argument list");

   _vars_rep_check.insert(var);

   auto & prototype = ctx.proc_prototypes.data[id].second;

   if (!var.empty())
   {
      prototype.parameters.push_back(
         func_param_t(
            var, var_type, vect_size, reference, array_type));
   }
}


/* -------------------------------------------------------------------------- */

stmt_func_t::stmt_cl_t stmt_func_t::get_cl() const throw()
{
   return stmt_cl_t::FUNC_BEGIN;
}


/* -------------------------------------------------------------------------- */

} // namespace nu


/* -------------------------------------------------------------------------- */

